package br.com.fiap.beans;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;

import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.beanutils.BeanUtils;

import br.com.fiap.dao.ClienteDAO;
import br.com.fiap.dao.LoginDAO;
import br.com.fiap.entity.Cliente;
import br.com.fiap.entity.Login;

@Named
@ManagedBean
@SessionScoped
public class ClienteBean extends AbstractBeanAcessor implements Serializable {

	private static final long serialVersionUID = 2156716669934292152L;
	
	@Inject
	private ClienteDAO clienteDAO;
	
	@Inject
	private LoginDAO loginDAO;
	
	private Cliente cliente = new Cliente();
	private Login login = new Login();

	public Cliente getCliente() {
		return cliente;
	}

	public void setCliente(Cliente cliente) {
		this.cliente = cliente;
	} 
	
	public Login getLogin() {
		return login;
	}

	public void setLogin(Login login) {
		this.login = login;
	}

	public String novoCliente() {
		this.cliente = new Cliente();
		return "/cliente/cadastro-cliente";
	}
	
	public String cadastrarCliente() {
		
		getLogin().setCliente(this.cliente);
		
		loginDAO.saveOrUpdate(this.login);
		
		this.login = new Login();
		
		return "/cliente/login";
		
	}
	
	public String salvarDados() {
		
		clienteDAO.saveOrUpdate(this.cliente);
		
		this.cliente = new Cliente();
		
		return "/cliente/sucesso-alteracao";
		
	}
	
	public String voltar() {
			
			return "/cliente/login";
			
		}
	
	public String recuperarCliente(Long id) {
		Cliente persistedClient = clienteDAO.findById(id);
		
		try {
			BeanUtils.copyProperties(cliente, persistedClient);
		} catch (IllegalAccessException e) {
			System.out.println("Erro copyProperties.");
		} catch (InvocationTargetException e) {
			System.out.println("Erro copyProperties.");
		}
		
		return "/cliente/cadastro-cliente";
	}
	
}
